package com.koomii.common.util;

import java.io.Reader;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

/**
 * json工具
 *
 */
public class JsonUtil {
	private final static Logger log = LogManager.getLogger(JsonUtil.class);
    public static Gson g = new Gson();
    private static Gson t = null;
    static {
        if (t == null) {
            t=new Gson();
        }
    }
    /**
     * 将对象转换成json格式
     * @param ts
     * @return
     */
    public static String objectToJson(Object ts) {
        String jsonStr = null;
        if (t != null) {
            jsonStr = t.toJson(ts);
        }
        return jsonStr;
    }
    /**
     * 将对象转换成json格式(并自定义日期格式)
     * 
     * @param ts
     * @return
     */
	    public static String objectToJson(Object ts, final String dateformat) {
	        String jsonStr = null;
	        t = new GsonBuilder().registerTypeHierarchyAdapter(Date.class, new JsonSerializer<Date>() {
	            public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
	                SimpleDateFormat format = new SimpleDateFormat(dateformat);
	                return new JsonPrimitive(format.format(src));
	            }
	        }).setDateFormat(dateformat).create();
	        if (t != null) {
	            jsonStr = t.toJson(ts);
	        }
	        return jsonStr;
	    }
        /**
         * 将json格式转换成list对象
         * @param jsonStr
         * @return
         */
        public static List<?> jsonToList(String jsonStr) {
            List<?> objList = null;
            if (t != null) {
                java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<?>>() {}.getType();
                objList = t.fromJson(jsonStr, type);
            }
            return objList;
        }
        /**
         * 将json格式转换成list对象，并准确指定类型
         * @param jsonStr
         * @param type
         * @return
         */
        public static List<?> jsonToList(String jsonStr, java.lang.reflect.Type type) {
            List<?> objList = null;
            if (t != null) {
                objList = t.fromJson(jsonStr, type);
            }
            return objList;
        }
        
        public static List<?>jsonToList(String jsonStr,java.lang.reflect.Type type, final String pattern) {
        	List<?> objList = null;
            t = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                        throws JsonParseException {
                    SimpleDateFormat format = new SimpleDateFormat(pattern);
                    String dateStr = json.getAsString();
                    try {
                    	if(StringUtils.isNotEmpty(dateStr)){
                    		 return format.parse(dateStr);
                    	}
                    } catch (ParseException e) {
                        //e.printStackTrace();
                        log.info("jsonToList(String jsonStr,java.lang.reflect.Type type, final String pattern)  日期解析发生异常:"+dateStr);
                    }
                    return null;
                }
            }).setDateFormat(pattern).create();
            if (t != null) {
            	objList = t.fromJson(jsonStr, type);
            }
            return objList;
        }
        /**
         * 将json格式转换成map对象
         * @param jsonStr
         * @return
         */
        public static Map<?, ?> jsonToMap(String jsonStr) {
            Map<?, ?> objMap = null;
            if (t != null) {
                java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<Map<?, ?>>() {}.getType();
                objMap = t.fromJson(jsonStr, type);
            }
            return objMap;
        }
        /**
         * 将json转换成bean对象
         * @param jsonStr
         * @return
         */
        public static Object jsonToBean(String jsonStr, Class<?> cl) {
            Object obj = null;
            if (t != null) {
                obj = t.fromJson(jsonStr, cl);
            }
            return obj;
        }
        /**
         * 将json转换成bean对象(并自定义日期格式)
         * @param jsonStr
         * @param cl
         * @return
         */
        @SuppressWarnings("unchecked")
        public static <T> T jsonToBean(String jsonStr, Class<T> cl, final String pattern) {
            Object obj = null;
            t = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                        throws JsonParseException {
                    SimpleDateFormat format = new SimpleDateFormat(pattern);
                    String dateStr = json.getAsString();
                    try {
                    	if(StringUtils.isNotEmpty(dateStr)){
                    		 return format.parse(dateStr);
                    	}
                    } catch (ParseException e) {
                        //e.printStackTrace();
                        log.info("jsonToList(String jsonStr,java.lang.reflect.Type type, final String pattern)  日期解析发生异常:"+dateStr);
                    }
                    return null;
                }
            }).setDateFormat(pattern).create();
            if (t != null) {
                obj = t.fromJson(jsonStr, cl);
            }
            return (T) obj;
        }
        /**
         * 将json转换成bean对象(并自定义日期格式)
         * @param jsonStr
         * @param type
         * @param pattern 日期的格式
         * @return
         */
        @SuppressWarnings("unchecked")
        public static <T> T jsonToBean(String jsonStr,java.lang.reflect.Type type, final String pattern) {
            Object obj = null;
            t = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                        throws JsonParseException {
                    SimpleDateFormat format = new SimpleDateFormat(pattern);
                    String dateStr = json.getAsString();
                    try {
                    	if(StringUtils.isNotEmpty(dateStr)){
                    		 return format.parse(dateStr);
                    	}
                    } catch (ParseException e) {
                        //e.printStackTrace();
                        log.info("jsonToList(String jsonStr,java.lang.reflect.Type type, final String pattern)  日期解析发生异常:"+dateStr);
                    }
                    return null;
                }
            }).setDateFormat(pattern).create();
            if (t != null) {
                obj = t.fromJson(jsonStr, type);
            }
            return (T) obj;
        }
        /**
         * 将json转换成bean对象(并自定义日期格式)
         * @param jsonReader
         * @param cl
         * @return
         */
        @SuppressWarnings("unchecked")
        public static <T> T jsonToBean(Reader jsonReader, Class<T> cl, final String pattern) {
            Object obj = null;
            t = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                        throws JsonParseException {
                    SimpleDateFormat format = new SimpleDateFormat(pattern);
                    String dateStr = json.getAsString();
                    try {
                    	if(StringUtils.isNotEmpty(dateStr)){
                    		 return format.parse(dateStr);
                    	}
                    } catch (ParseException e) {
                        //e.printStackTrace();
                        log.info("jsonToList(String jsonStr,java.lang.reflect.Type type, final String pattern)  日期解析发生异常:"+dateStr);
                    }
                    return null;
                }
            }).setDateFormat(pattern).create();
            if (t != null) {
                obj = t.fromJson(jsonReader, cl);
            }
            return (T) obj;
        }
        /**
         * 根据key获得value值
         * @param jsonStr
         * @param key
         * @return
         */
        public static Object getJsonValue(String jsonStr, String key) {
            Object rulsObj = null;
            Map<?, ?> rulsMap = jsonToMap(jsonStr);
            if (rulsMap != null && rulsMap.size() > 0) {
                rulsObj = rulsMap.get(key);
            }
            return rulsObj;
        }
}
